package com.mysoft.gfyx.common.rpc.bigdata;

import com.mysoft.gfyx.common.concurrency.CacheAgentService;
import com.mysoft.gfyx.common.rpc.bigdata.dto.GetTokenResponseDto;
import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


public class BigDataClientConfiguration implements RequestInterceptor {
    protected CacheAgentService cacheAgentService;
    protected String authHost;
    protected String appId;
    protected String appKey;
    protected String appSecret;


    public BigDataClientConfiguration(String authHost, String appId, String appKey, String appSecret, CacheAgentService cacheAgentService) {
        this.authHost = authHost;
        this.appId = appId;
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.cacheAgentService = cacheAgentService;
    }

    @Override
    public void apply(RequestTemplate template) {
        // 1.先从缓存获取token,获取不到则掉接口获取,并保存到缓存
        String cacheKey = "gfyx:bigdata:token";
        String token = cacheAgentService.getCachedData(cacheKey);
        if (token != null && !token.equals("")) {
            template.query("jwt", token);
            return;
        }

        // 调用接口获取Token
        token = getToken();
        if (token != null && !token.equals("")) {
            template.query("jwt", token);
            cacheAgentService.setCacheDataAndSetExpiredTime(cacheKey, token, 7000);
        }

        System.out.println("token:"+token);
    }

    protected String getToken() {
        BigDataAuthService bigDataAuthService = Feign.builder()
                .encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
                .target(BigDataAuthService.class, authHost);

        GetTokenResponseDto getTokenResponseDto = bigDataAuthService.getToken(appId, appKey, appSecret);

        if (getTokenResponseDto != null && getTokenResponseDto.getData() != null && getTokenResponseDto.getData().get("token") != null) {
            return getTokenResponseDto.getData().get("token");
        }
        return "";
    }
}
